package com.lijianan.Controller;


import com.lijianan.entity.*;
import com.lijianan.service.*;
import com.lijianan.utils.DateSplit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@RestController
@RequestMapping("/api")
@CrossOrigin  //支持跨域

public class UserController {
    @Autowired
    private UserServiceImpl userServiceImpl;

    @Autowired
    private MultimediaEquipmentServiceImpl multimediaEquipmentServiceImpl;

    @Autowired
    private MeetingRoomServiceImpl meetingRoomServiceImpl;

    @Autowired
    private MeetingRoomEquipmentServiceImpl meetingRoomEquipmentServiceImpl;

    @Autowired
    private BookingServiceImpl bookingServiceImpl;

    @Autowired
    private BookingEquipmentServiceImpl bookingEquipmentServiceImpl;


    //用户接口
    @PostMapping("/users/register")
    public ResponseEntity<Object> register(@RequestBody Registeruser registeruser) {
        // 简单的验证，可根据实际需求修改
        String username = registeruser.getAccount();
        String password = registeruser.getPassword();
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "用户名和密码不能为空");
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        if (username.length()>15){
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "账号长度不能多于15位");
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        // 可以添加更多的密码复杂度验证
        if (password.length() < 6) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "密码长度不能少于6位");
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }

        try {
            boolean success = userServiceImpl.register(registeruser.getAccount(),registeruser.getPassword(),
                    registeruser.getName(),registeruser.getCompanyName(),registeruser.getPhoneNumber());
            if (success) {
                return new ResponseEntity<>(HttpStatus.CREATED);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "注册失败，请稍后再试");
                return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常，请稍后再试");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/users/login")
    public ResponseEntity<Object> login(@RequestBody Loginuser loginuser){
        try {
            boolean success = userServiceImpl.login(loginuser.getAccount(),loginuser.getPassword());
            if(success){
                User user=userServiceImpl.selectByAccount(loginuser.getAccount());
                if(user.getIs_frozen()&&!user.getIs_approved()){
                    Map<String, String> errorResponse = new HashMap<>();
                    errorResponse.put("message", "账户已被冻结或未通过审核");
                    return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
                }
                Map<String, Object> claims = new HashMap<>();
                claims.put("account", loginuser.getAccount());
                String token=JwtUtils.generateJwt(claims);

                Map<String, Object> response = new HashMap<>();
                User query=userServiceImpl.selectByAccount(loginuser.getAccount());
                response.put("user", query);
                response.put("token", token);
                return new ResponseEntity<>(response, HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "账户或密码错误");
                return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
            }
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细的异常堆栈信息
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/users/logout")
    public ResponseEntity<Object> logout(@RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少/无效/过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀

        try {
            return new ResponseEntity<>(HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常，验证 token 时出错");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/users/profile")
    public ResponseEntity<Object> getCustomerProfile(@RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少/无效/过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀

        try {
            // 验证 token
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            User user = userServiceImpl.selectByAccount(account);
            if (user != null) {
                return new ResponseEntity<>(user, HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "未找到用户信息");
                return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/users/profile")
    public ResponseEntity<Object> updateCustomerProfile(@RequestHeader(name = "Authorization", required = false) String authorizationHeader,
                                                        @RequestBody UserInfo userInfo) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀

        try {
            // 验证 token
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            String name = userInfo.getName();
            String companyName = userInfo.getCompanyName();
            String phoneNumber = userInfo.getPhoneNumber();

            // 简单验证用户信息
            if (name == null || companyName == null || phoneNumber == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "用户信息无效");
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }

            boolean success = userServiceImpl.modifyInfo(account, name, companyName, phoneNumber);
            if (success) {
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "服务端异常，更新用户信息失败");
                return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/users/password")
    public ResponseEntity<Object> updatePassword(@RequestHeader(name = "Authorization", required = false) String authorizationHeader,
                                                 @RequestBody PasswordInfo passwordInfo) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            String oldPassword = passwordInfo.getOldPassword();
            String newPassword = passwordInfo.getNewPassword();

            if (newPassword == null || newPassword.length() < 6) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "新密码格式错误，长度不能少于6位");
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }

            boolean success = userServiceImpl.changePassword(account, oldPassword, newPassword);
            if (success) {
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "旧密码错误");
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    //客户接口
    @PostMapping("/customers/check-account")
    public ResponseEntity<Object> checkAccountAvailability(@RequestBody AccountCheck accountCheck) {
        String account = accountCheck.getAccount();
        try {
            User user = userServiceImpl.selectByAccount(account);
            if (user == null) {
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.CONFLICT);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/customers/meeting-rooms")
    public ResponseEntity<Object> getAllMeetingRooms(@RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            List<MeetingRoom> meetingRooms = meetingRoomServiceImpl.selectAll();
            List<Map<String, Object>> meetingRoomList = new ArrayList<>();
            for (MeetingRoom meetingRoom : meetingRooms) {
                Map<String, Object> bookingInfo = new HashMap<>();
                bookingInfo.put("room_id", meetingRoom.getRoom_id());
                bookingInfo.put("name", meetingRoom.getName());
                bookingInfo.put("type", meetingRoom.getType());
                bookingInfo.put("seating_capacity", meetingRoom.getSeating_capacity());
                bookingInfo.put("price_per_hour", meetingRoom.getPrice_per_hour());
                bookingInfo.put("current_status", meetingRoom.getCurrent_status());
                bookingInfo.put("created_at", meetingRoom.getCreated_at());
                bookingInfo.put("updated_at", meetingRoom.getUpdated_at());
                List<MultimediaEquipment> meetingRoomEquipments =
                        meetingRoomEquipmentServiceImpl.selectMultimediaEquipmentsByRoomId(meetingRoom.getRoom_id());
                List<String> equipments = new ArrayList<>();
                for (MultimediaEquipment multimediaEquipment : meetingRoomEquipments) {
                    equipments.add(multimediaEquipment.getName());
                }
                bookingInfo.put("equipments", equipments);
                meetingRoomList.add(bookingInfo);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("data", meetingRoomList);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/customers/meeting-rooms/{roomId}")
    public ResponseEntity<Object> getSingleMeetingRoom(@PathVariable int roomId, @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            MeetingRoom meetingRoom = meetingRoomServiceImpl.selectByRoomId(roomId);
            if (meetingRoom != null) {
                Map<String, Object> response = new HashMap<>();
                response.put("data", meetingRoom);
                return new ResponseEntity<>(response, HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "会议室不存在");
                return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/customers/ablemeeting-rooms")
    public ResponseEntity<Object> getAvailableMeetingRooms(
            @RequestHeader(name = "Authorization", required = false) String authorizationHeader,
            @RequestBody BookingParam bookingParam) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            String useStartDate = bookingParam.getUseStartDate();
            String useStartTime = bookingParam.getUseStartTime();
            String useEndDate = bookingParam.getUseEndDate();
            String useEndTime = bookingParam.getUseEndTime();
            int attendeeCount = bookingParam.getAttendeeCount();
            List<String> requiredEquipment = bookingParam.getRequiredEquipment();

            System.out.println(bookingParam);
            // 验证参数
            if (useStartDate == null || useStartTime == null || useEndDate == null || useEndTime == null
                    || attendeeCount <0 || requiredEquipment == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "请求参数不完整");
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }

            String nowStartDate= bookingParam.getUseStartDate();
            String nowStartTime= bookingParam.getUseStartTime();
            String dateStr2 = nowStartDate+" "+nowStartTime;
            DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime localDateTime = LocalDateTime.parse(dateStr2, formatter2);
            Date StartTime = Date.from(localDateTime.atZone(java.time.ZoneId.systemDefault()).toInstant());
            System.out.println("yyyy-MM-dd HH:mm:ss 格式解析结果: " + StartTime);

            String nowEndDate= bookingParam.getUseEndDate();
            String nowEndTime= bookingParam.getUseEndTime();
            dateStr2 = nowEndDate+" "+nowEndTime;
            formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            localDateTime = LocalDateTime.parse(dateStr2, formatter2);
            Date EndTime = Date.from(localDateTime.atZone(java.time.ZoneId.systemDefault()).toInstant());
            System.out.println("yyyy-MM-dd HH:mm:ss 格式解析结果: " + EndTime);

            System.out.println(StartTime);
            System.out.println(EndTime);

            // 调用 service 方法获取可用会议室信息
            List<MeetingRoom> availableRooms = meetingRoomServiceImpl.siftMeetingRoom(StartTime, EndTime, attendeeCount ,requiredEquipment);
            List<Map<String, Object>> MeetingRoomList = new ArrayList<>();
            for (MeetingRoom meetingRoom : availableRooms) {
                Map<String, Object> MeetingRoomInfo = new HashMap<>();
                MeetingRoomInfo.put("meetingRoomId", meetingRoom.getRoom_id());
                MeetingRoomInfo.put("meetingRoomName", meetingRoom.getName());
                MeetingRoomList.add(MeetingRoomInfo);
            }
            Map<String, Object> response = new HashMap<>();
            response.put("data", MeetingRoomList);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/customers/bookings/{roomId}")
    public ResponseEntity<Object> bookMeetingRoom(@PathVariable int roomId,
                                                  @RequestHeader(name = "Authorization", required = false) String authorizationHeader,
                                                  @RequestBody BookingParam bookingParam) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            System.out.println(bookingParam);
            String useStartDate = bookingParam.getUseStartDate();
            String useStartTime = bookingParam.getUseStartTime();
            String useEndDate = bookingParam.getUseEndDate();
            String useEndTime = bookingParam.getUseEndTime();
            int attendeeCount = bookingParam.getAttendeeCount();
            List<String> requiredEquipment = bookingParam.getRequiredEquipment();

            // 简单验证预订信息
            if (useStartDate == null || useStartTime == null || useEndDate == null || useEndTime == null
                    || attendeeCount < 0 || requiredEquipment == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "预订信息无效");
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }

            String nowStartDate= bookingParam.getUseStartDate();
            String nowStartTime= bookingParam.getUseStartTime();
            String dateStr2 = nowStartDate+" "+nowStartTime;
            DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime localDateTime = LocalDateTime.parse(dateStr2, formatter2);
            Date StartTime = Date.from(localDateTime.atZone(java.time.ZoneId.systemDefault()).toInstant());
            System.out.println("yyyy-MM-dd HH:mm:ss 格式解析结果: " + StartTime);

            String nowEndDate= bookingParam.getUseEndDate();
            String nowEndTime= bookingParam.getUseEndTime();
            dateStr2 = nowEndDate+" "+nowEndTime;
            formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            localDateTime = LocalDateTime.parse(dateStr2, formatter2);
            Date EndTime = Date.from(localDateTime.atZone(java.time.ZoneId.systemDefault()).toInstant());
            System.out.println("yyyy-MM-dd HH:mm:ss 格式解析结果: " + EndTime);

            User user=userServiceImpl.selectByAccount(account);
            MeetingRoom meetingRoom=meetingRoomServiceImpl.selectByRoomId(roomId);
            boolean success=bookingServiceImpl.addBooking(user.getUser_id(),roomId,StartTime,EndTime,attendeeCount,meetingRoom.getPrice_per_hour(),requiredEquipment);
            if (success) {
                return new ResponseEntity<>(HttpStatus.CREATED);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "预订失败");
                return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/customers/bookings")
    public ResponseEntity<Object> getBookingList(@RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");
            User user=userServiceImpl.selectByAccount(account);
            List<Booking> bookings = bookingServiceImpl.selectByCustomerId(user.getUser_id());
            List<Map<String, Object>> bookingList = new ArrayList<>();
            for (Booking booking : bookings) {
                Map<String, Object> bookingInfo = new HashMap<>();
                bookingInfo.put("bookingId", booking.getBooking_id());
                bookingInfo.put("meetingRoomName", booking.getRoom_id());
                bookingInfo.put("useStartTime", booking.getUse_time_start());
                bookingInfo.put("useEndTime", booking.getUse_time_end());
                boolean canCancel=bookingServiceImpl.judgeRoomCanCancel(booking);
                boolean canComplete= bookingServiceImpl.judgeBookingCanComplete(booking);
                if (canCancel) {
                    if("pending".equals(booking.getCancellation_status())){
                        String nowStatus="pending";
                        bookingInfo.put("status", nowStatus);
                    }else if("approved".equals(booking.getCancellation_status())){
                        String nowStatus="approved";
                        bookingInfo.put("status", nowStatus);
                    }else{
                        String nowStatus="cancelable";
                        bookingInfo.put("status", nowStatus);
                    }
                }else if (canComplete){
                    String nowStatus="achievable";
                    bookingInfo.put("status", nowStatus);
                }else{
                    bookingInfo.put("status", booking.getStatus());
                }
                bookingList.add(bookingInfo);

            }
            Map<String, Object> response = new HashMap<>();
            response.put("data", bookingList);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/customers/bookings/{bookingId}")
    public ResponseEntity<Object> getBookingDetail(@PathVariable int bookingId, @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            Booking booking = bookingServiceImpl.selectByBookingId(bookingId);
            if (booking == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "预订不存在");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }

            MeetingRoom meetingRoom = meetingRoomServiceImpl.selectByRoomId(booking.getRoom_id());
            List<MultimediaEquipment> equipmentList = bookingEquipmentServiceImpl.selectMultimediaEquipmentsByBookingId(bookingId);
            List<String> equipmentNames = new ArrayList<>();
            for (MultimediaEquipment equipment : equipmentList) {
                equipmentNames.add(equipment.getName());
            }

            Map<String, Object> response = new HashMap<>();
            response.put("meetingRoomName", meetingRoom.getName());
            response.put("useStartTime", booking.getUse_time_start());
            response.put("useEndTime", booking.getUse_time_end());
            response.put("attendeeCount", booking.getAttendee_count());
            response.put("requiredEquipment", equipmentNames);
            boolean canCancel=bookingServiceImpl.judgeRoomCanCancel(booking);
            boolean canComplete= bookingServiceImpl.judgeBookingCanComplete(booking);
            if (canCancel) {
                if("pending".equals(booking.getCancellation_status())){
                    String nowStatus="pending";
                    response.put("status", nowStatus);
                }else if("approved".equals(booking.getCancellation_status())){
                    String nowStatus="approved";
                    response.put("status", nowStatus);
                }else{
                    String nowStatus="cancelable";
                    response.put("status", nowStatus);
                }
            }else if (canComplete){
                String nowStatus="achievable";
                response.put("status", nowStatus);
            }else{
                response.put("status", booking.getStatus());
            }
            response.put("price", booking.getAmount());
            response.put("refund_percentage", booking.getRefund_percentage());
            response.put("refund_amount", booking.getRefund_amount());

            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @DeleteMapping("/customers/bookings/{bookingId}")
    public ResponseEntity<Object> cancelBooking(@PathVariable int bookingId, @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            User user = userServiceImpl.selectByAccount(account);
            Booking booking = bookingServiceImpl.selectByBookingId(bookingId);
            boolean success = bookingServiceImpl.submitCancelReservation(user.getUser_id(), booking.getRoom_id());
            if (success) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "预订不存在");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/customers/bookings/{bookingId}/payments")
    public ResponseEntity<Object> payBooking(@PathVariable int bookingId, @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            boolean success = bookingServiceImpl.payment(bookingId);
            if (success) {
                return new ResponseEntity<>(HttpStatus.CREATED);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "不存在 / 未需支付 / 已支付");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/customers/bookings/{bookingId}/confirm")
    public ResponseEntity<Object> confirmCancelApprovedBooking(@PathVariable int bookingId, @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            boolean success = bookingServiceImpl.confirmCancelSuccess(bookingId);
            if (success) {
                return new ResponseEntity<>(HttpStatus.CREATED);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "确认失败");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/customers/bookings/{bookingId}/complete")
    public ResponseEntity<Object> confirmComplete(@PathVariable int bookingId, @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            boolean success = bookingServiceImpl.changeStatusToCompleted(bookingId);
            if (success) {
                return new ResponseEntity<>(HttpStatus.CREATED);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "确认失败");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    //员工接口
    @GetMapping("/staff/meeting-rooms/status")
    public ResponseEntity<Object> getMeetingRoomStatus(@RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            List<MeetingRoom> meetingRooms = meetingRoomServiceImpl.selectAll();
            List<Map<String, Object>> roomStatusList = new ArrayList<>();
            for (MeetingRoom meetingRoom : meetingRooms) {
                Map<String, Object> roomStatus = new HashMap<>();
                roomStatus.put("meetingRoomId", meetingRoom.getRoom_id());
                roomStatus.put("meetingRoomName", meetingRoom.getName());
                roomStatus.put("status", meetingRoom.getCurrent_status());
                roomStatusList.add(roomStatus);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("data", roomStatusList);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/staff/meeting-rooms/{meetingRoomId}/using")
    public ResponseEntity<Object> setMeetingRoomUsing(@PathVariable int meetingRoomId, @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            boolean success = meetingRoomServiceImpl.changeStatusToUse(meetingRoomId);
            if (success) {
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "会议室不存在");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/staff/meeting-rooms/{meetingRoomId}/idle")
    public ResponseEntity<Object> setMeetingRoomIdle(@PathVariable int meetingRoomId, @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        System.out.println(meetingRoomId);
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            boolean success = meetingRoomServiceImpl.changeStatusToFree(meetingRoomId);
            if (success) {
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "会议室不存在");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/staff/bookings/cancancel")
    public ResponseEntity<Object> getCancelableBookings(@RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            List<Booking> bookings = bookingServiceImpl.selectByCancelStatusForPending();
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (Booking booking : bookings) {
                Map<String, Object> bookingInfo = new HashMap<>();
                bookingInfo.put("bookingId", String.valueOf(booking.getBooking_id()));
                // 这里可以添加更多会议室信息的获取，假设MeetingRoomServiceImpl有相应方法获取会议室信息
                MeetingRoom meetingRoom = meetingRoomServiceImpl.selectByRoomId(booking.getRoom_id());
                bookingInfo.put("meetingRoom", meetingRoom);
                resultList.add(bookingInfo);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("data", resultList);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/staff/meeting-rooms/{meetingRoomId}/maintenance")
    public ResponseEntity<Object> setMeetingRoomMaintenance(@PathVariable int meetingRoomId, @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            boolean success = meetingRoomServiceImpl.changeStatusToRepair(meetingRoomId);
            if (success) {
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "会议室不存在");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/staff/bookings/{bookingId}/cancel")
    public ResponseEntity<Object> handleCancelBooking(@PathVariable int bookingId, @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");
            User staff = userServiceImpl.selectByAccount(account);

            System.out.println("handleCancelBooking"+bookingId);

            boolean success= bookingServiceImpl.changeCancelStatusToApproved(bookingId,staff.getUser_id());
            if (success) {
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "预订不存在");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/admins/meeting-rooms")
    public ResponseEntity<Object> addMeetingRoom(
            @RequestHeader(name = "Authorization", required = false) String authorizationHeader,
            @RequestBody CreateRoom createRoom) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            boolean success = meetingRoomServiceImpl.addMeetingRoom(createRoom.getName(),
                    createRoom.getType(), createRoom.getSeatingCapacity(), createRoom.getPrice(),
                    createRoom.getMultimediaSupport());
            if(success){
                return new ResponseEntity<>(HttpStatus.CREATED);
            }else{
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "会议室信息无效");
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/admins/meeting-rooms/{meetingRoomId}")
    public ResponseEntity<Object> updateMeetingRoom(
            @PathVariable int meetingRoomId,
            @RequestHeader(name = "Authorization", required = false) String authorizationHeader,
            @RequestBody CreateRoom createRoom) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            // 简单验证会议室信息
            if (createRoom.getName() == null || createRoom.getType() == null || createRoom.getSeatingCapacity() <0
                    || createRoom.getMultimediaSupport() == null || createRoom.getPrice() <0) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "会议室信息无效");
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }

            System.out.println(createRoom.getMultimediaSupport());

            boolean success = meetingRoomServiceImpl.updateMeetingRoom(meetingRoomId, createRoom.getName(), createRoom.getType(),
                    createRoom.getSeatingCapacity(),createRoom.getPrice(),createRoom.getMultimediaSupport());
            if (success) {
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "会议室不存在");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @DeleteMapping("/admins/meeting-rooms/{meetingRoomId}")
    public ResponseEntity<Object> deleteMeetingRoom(
            @PathVariable int meetingRoomId,
            @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            boolean success = meetingRoomServiceImpl.deleteMeetingRoom(meetingRoomId);
            if (success) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "会议室不存在");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/admins/users")
    public ResponseEntity<Object> getUsers(@RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            List<User> userList = userServiceImpl.selectAll();
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (User user : userList) {
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("id", String.valueOf(user.getUser_id()));
                userInfo.put("account", user.getAccount());
                userInfo.put("role", user.getRole());
                userInfo.put("name", user.getName());
                userInfo.put("isApproved", user.getIs_approved());
                userInfo.put("isFrozen", user.getIs_frozen());
                resultList.add(userInfo);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("data", resultList);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/admins/users/{userId}")
    public ResponseEntity<Object> getUserDetail(@PathVariable int userId, @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            User user = userServiceImpl.selectByUserId(userId);
            if (user != null) {
                Map<String, Object> response = new HashMap<>();
                response.put("account", user.getAccount());
                response.put("password", user.getPassword());
                response.put("role", user.getRole());
                response.put("name", user.getName());
                response.put("companyName", user.getCompany_name());
                response.put("phoneNumber", user.getPhone_number());
                response.put("isApproved", user.getIs_approved());
                response.put("isFrozen", user.getIs_frozen());
                System.out.println(response);
                return new ResponseEntity<>(response, HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "用户不存在");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/admins/updateprofile")
    public ResponseEntity<Object> updateUserProfile(@RequestHeader(name = "Authorization", required = false) String authorizationHeader,
                                                    @RequestBody UpdateUser updateUser) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            System.out.println(updateUser);
            boolean success = userServiceImpl.modifyInfo(updateUser.getAccount(),updateUser.getName(),
                    updateUser.getCompanyName(), updateUser.getPhoneNumber())
                    &&
                    userServiceImpl.modifyRole(updateUser.getAccount(),updateUser.getRole());

            if (success) {
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "更新失败,用户信息无效");
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/admins/users/{userId}/approve")
    public ResponseEntity<Object> approveUserAccount(@PathVariable int userId,
                                                     @RequestHeader(name = "Authorization", required = false) String authorizationHeader,
                                                     @RequestBody ApproveUser approveUser) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            System.out.println(approveUser);

            User user = userServiceImpl.selectByUserId(userId);
            if (user == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "用户不存在");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }

            boolean success = userServiceImpl.changeStateToApprove(userId);
            if (success) {
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "审核失败");
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/api/admins/users/{userId}/freeze")
    public ResponseEntity<Object> freezeUserAccount(@PathVariable int userId,
                                                    @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            User user = userServiceImpl.selectByUserId(userId);
            if (user == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "用户不存在");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }

            boolean success = userServiceImpl.changeStateToFrozen(userId);
            if (success) {
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "冻结失败");
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/admins/users/{userId}/removefreeze")
    public ResponseEntity<Object> removeFreezeUserAccount(@PathVariable int userId,
                                                    @RequestHeader(name = "Authorization", required = false) String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "缺少 / 无效 / 过期 token");
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
        }

        String token = authorizationHeader.substring(7);

        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            String account = (String) claims.get("account");

            User user = userServiceImpl.selectByUserId(userId);
            if (user == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "用户不存在");
                return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }

            boolean success = userServiceImpl.removeFrozenState(userId);
            if (success) {
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "解冻失败");
                return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务端异常");
            return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
